Page({
  data: {
    token: '',
    coupons: [],
    loading: false,
    currentPage: 1,
    totalPages: 1,
    activeTab: 0, // 默认选中第1个标签（未使用）
  },

  onLoad(options) {
    const token = wx.getStorageSync('token');
    if (token) {
      this.setData({ token }, () => {
        const { status = 'unused' } = options;
        let activeTab = 0;
        let apiStatus = 0;
        // 根据入口参数映射标签和接口状态
        if (status === 'used') {
          activeTab = 1;
          apiStatus = 1;
        } else if (status === 'expired') {
          activeTab = 2;
          apiStatus = 2;
        }
        console.log('入口参数映射后的activeTab：', activeTab); // 确认值正确
        
        // 关键：先设置一个无效值（如-1），再设置目标值，强制组件重新渲染
        this.setData({ activeTab: -1 }, () => {
          this.setData({ activeTab }, () => {
            console.log('最终activeTab值：', this.data.activeTab); // 确认已更新
            this.fetchCoupons(apiStatus, true);
          });
        });
      });
    } else {
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => wx.navigateTo({ url: '/pages/login/login' }), 1500);
    }
  },

  changeTab(e) {
    const activeTab = e.detail.index; // 0/1/2
    const apiStatus = activeTab; // 直接用标签索引作为后端status（数字）
    console.log('标签切换：标签索引=', activeTab, '后端status=', apiStatus);
    this.setData({
      activeTab,
      coupons: [],
      currentPage: 1,
      totalPages: 1,
      loading: true
    }, () => {
      this.fetchCoupons(apiStatus, true);
    });
  },

  onReachBottom() {
    if (this.data.currentPage < this.data.totalPages && !this.data.loading) {
      this.setData({ 
        currentPage: this.data.currentPage + 1,
        loading: true
      });
      const apiStatus = this.data.activeTab; // 用当前标签索引作为status
      this.fetchCoupons(apiStatus, false);
    }
  },

  fetchCoupons(apiStatus, isReset) {
    // 校验参数是否为有效数字
    if (![0, 1, 2].includes(apiStatus)) {
      console.error('无效的status值：', apiStatus);
      wx.showToast({ title: '参数错误', icon: 'none' });
      this.setData({ loading: false });
      return;
    }

    const { token, currentPage } = this.data;
    if (!token) {
      this.setData({ loading: false });
      return;
    }

    this.setData({ loading: true });
    wx.showLoading({ title: '加载中...' });

    console.log('请求接口参数：', { status: apiStatus, page: currentPage, limit: 10 });
    wx.request({
      url: 'http://admin.bsmall.byesame.com/wx/coupon/mylist',
      method: 'GET',
      header: { 'x-byesame-token': token },
      data: { 
        status: apiStatus, // 传递数字（0/1/2）给后端
        page: currentPage, 
        limit: 10 
      },
      success: (res) => {
        console.log('接口返回：', res.data);
        if (res.data.errno === 0) {
          const { list = [], total = 0 } = res.data.data;
          const totalPages = Math.ceil(total / 10);
          const newCoupons = isReset ? list : [...this.data.coupons, ...list];
          this.setData({ coupons: newCoupons, totalPages });
        } else {
          wx.showToast({ title: res.data.errmsg || '获取失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('请求失败：', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      },
      complete: () => {
        this.setData({ loading: false });
        wx.hideLoading();
      }
    });
  },
  onShow() {
    // 错误示例：如果有这样的代码，会覆盖onLoad中设置的activeTab
    // this.setData({ activeTab: 0 }); 
  
    // 正确：只在需要时刷新数据，不修改activeTab
    if (this.data.token && this.data.coupons.length === 0) {
      this.fetchCoupons(this.data.activeTab, true);
    }
  }
});